package leetcode;

import java.util.HashMap;

public class code290 {
    public static void main(String[] args) {
        String pattern = "abba";
        String str = "dog cat cat dog";
        System.out.println(wordPattern(pattern,str));
    }

    public static boolean wordPattern(String pattern, String str) {
        //1.创建一个Hashmap，存放字符和字符串的对应关系
        HashMap<Character,String> map = new HashMap<>();

        //2.将字符串分割成单词
        String[] words = str.split(" ");

        //3.判断字符和单词的个数是否相等
        if(pattern.length()!=words.length) return false;

        //相等的话，遍历字符和单词
        for(int i=0;i<pattern.length();i++){
            char c = pattern.charAt(i);
            if(map.containsKey(c)){
                //如果map中已经存在该字符，则判断对应的字符串是否相等
                if(!map.get(c).equals(words[i])) return false;
            }else{
                //如果map中不存在该字符，则判断该字符串是否已经被使用过
                if(map.containsValue(words[i])) return false;
                map.put(c,words[i]);
            }
        }
        return true;

    }
}
